<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<template>
  <div class="aside-container">
    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <el-menu
      v-else
      :default-active="activeIndex"
      class="el-menu-vertical"
      :collapse="isCollapse"
      background-color="#304156"
      text-color="#bfcbd9"
      active-text-color="#409EFF"
      :unique-opened="true"
      :router="true"
      @select="handleSelect">

      <!-- 管理员菜单 -->
      <template v-if="userRole === 'ADMIN'">
        <el-menu-item index="/admin/dashboard">
          <el-icon><Monitor /></el-icon>
          <span>首页</span>
        </el-menu-item>

        <el-menu-item index="/admin/user-management">
          <el-icon><User /></el-icon>
          <span>用户管理</span>
        </el-menu-item>

<!--        <el-sub-menu index="2">-->
<!--          <template #title>-->
<!--            <el-icon><Setting /></el-icon>-->
<!--            <span>系统管理</span>-->
<!--          </template>-->
<!--          <el-menu-item index="/admin/role-management">角色管理</el-menu-item>-->
<!--          <el-menu-item index="/admin/menu-management">菜单管理</el-menu-item>-->
<!--          <el-menu-item index="/admin/dictionary-management">字典管理</el-menu-item>-->
<!--        </el-sub-menu>-->

<!--        <el-sub-menu index="3">-->
<!--          <template #title>-->
<!--            <el-icon><DataLine /></el-icon>-->
<!--            <span>数据统计</span>-->
<!--          </template>-->

<!--          <el-menu-item index="/admin/trace-stats">溯源统计</el-menu-item>-->
<!--          <el-menu-item index="/admin/farming-management">种植信息管理</el-menu-item>-->
<!--        </el-sub-menu>-->

        <el-menu-item index="/admin/log">
          <el-icon><Document /></el-icon>
          <span>系统日志</span>
        </el-menu-item>
      </template>

      <!-- 种植户菜单 -->
      <template v-if="userRole === 'FARMER'">
        <el-menu-item index="/farmer/dashboard">
          <el-icon><Monitor /></el-icon>
          <span>控制台</span>
        </el-menu-item>
        <el-menu-item index="/farmer/info-entry">
          <el-icon><Edit /></el-icon>
          <span>信息录入</span>
        </el-menu-item>
        <el-menu-item index="/farmer/qrcode">
          <el-icon><Promotion /></el-icon>
          <span>溯源码管理</span>
        </el-menu-item>
<!--        <el-menu-item index="/farmer/order">-->
<!--          <el-icon><Document /></el-icon>-->
<!--          <span>订单管理</span>-->
<!--        </el-menu-item>-->
<!--        <el-menu-item index="/farmer/stats">-->
<!--          <el-icon><DataAnalysis /></el-icon>-->
<!--          <span>种植统计</span>-->
<!--        </el-menu-item>-->
      </template>

      <!-- 经销商菜单 -->
      <template v-if="userRole === 'DEALER'">
        <el-menu-item index="/dealer/dashboard">
          <el-icon><Monitor /></el-icon>
          <span>控制台</span>
        </el-menu-item>
        <el-menu-item index="/dealer/order-management">
          <el-icon><Document /></el-icon>
          <span>订单管理</span>
        </el-menu-item>
        <el-menu-item index="/dealer/logistics-management">
          <el-icon><Van /></el-icon>
          <span>物流管理</span>
        </el-menu-item>
<!--        <el-menu-item index="/dealer/customer-management">-->
<!--          <el-icon><User /></el-icon>-->
<!--          <span>客户管理</span>-->
<!--        </el-menu-item>-->

      </template>

      <!-- 通用菜单项 -->
      <el-menu-item :index="userRole === 'ADMIN' ? '/admin/profile' : userRole === 'FARMER' ? '/farmer/profile' : '/dealer/profile'">
        <el-icon><Setting /></el-icon>
        <span>个人设置</span>
      </el-menu-item>
    </el-menu>
  </div>
</template>

<script>
import { computed, ref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import {
  Monitor,
  User,
  Setting,
  // DataLine,
  Document,
  Edit,
  Promotion,
  // DataAnalysis,
  Van,
  Loading
} from '@element-plus/icons-vue'

export default {
  name: 'CommonAside',
  components: {
    Monitor,
    User,
    Setting,
    // DataLine,
    Document,
    Edit,
    Promotion,
    // DataAnalysis,
    Van,
    Loading
  },
  props: {
    isCollapse: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const store = useStore()
    const route = useRoute()

    const activeIndex = ref(route.path)
    const userRole = ref('') // 初始为空，等待从数据库获取
    const loading = ref(true) // 添加加载状态

    // 监听路由变化
    watch(() => route.path, (newPath) => {
      activeIndex.value = newPath
      console.log('路由变化，当前路径:', newPath)
    })

    onMounted(() => {
      loading.value = true
      console.log('组件挂载，开始获取用户角色')

      // 从localStorage获取用户信息
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        if (userInfo && userInfo.role) {
          userRole.value = userInfo.role
          console.log('从localStorage获取角色:', userRole.value)
        }
      } catch (e) {
        console.error('解析用户信息错误:', e)
      }

      // 从store获取用户角色信息（优先级更高）
      if (store.getters.userRole) {
        userRole.value = store.getters.userRole
        console.log('从store获取角色:', userRole.value)
      }

      // 如果仍然没有角色信息，从API获取
      if (!userRole.value) {
        console.log('没有找到用户角色信息，从API获取')
        // 假设有这样的API
        // 注意：在实际项目中，您需要实现这个API或使用现有的API
        getUserRoleFromAPI()
          .then(role => {
            if (role) {
              userRole.value = role
              // 将获取到的角色保存到store
              store.commit('SET_USER_ROLE', role)
            } else {
              // 如果API也没返回角色，可能是未登录状态
              console.warn('无法获取用户角色，可能是未登录状态')
            }
          })
          .catch(err => {
            console.error('获取用户角色失败:', err)
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        loading.value = false
      }

      console.log('最终使用角色:', userRole.value)
    })

    const isCollapsed = computed(() => {
      return props.isCollapse || store.state.isCollapse
    })

    // 添加菜单选择处理方法
    const handleSelect = (index, indexPath) => {
      console.log('菜单选择:', index, indexPath)
      // 不需要手动导航，因为已经设置了:router="true"
      // 只需要记录一下以便调试
    }

    // 模拟从API获取用户角色的函数
    // 在实际项目中，您需要替换为真实的API调用
    function getUserRoleFromAPI() {
      return new Promise((resolve, reject) => {
        // 模拟API请求延迟
        setTimeout(() => {
          try {
            // 这里应该是真实的API调用
            // 例如：axios.get('/api/user/role').then(res => resolve(res.data.role))

            // 临时解决方案：从localStorage获取
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
            resolve(userInfo.role || '')
          } catch (error) {
            reject(error)
          }
        }, 500)
      })
    }

    return {
      activeIndex,
      userRole,
      isCollapsed,
      handleSelect,
      loading
    }
  }
}
</script>

<style scoped>
.aside-container {
  height: 100%;
  background-color: #304156;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
  min-height: 100%;
}

.el-menu-vertical.el-menu--collapse {
  min-height: 100%;
}

.el-menu {
  border-right: none;
}

/* 修复折叠菜单下的图标居中问题 */
.el-menu--collapse .el-menu-item .el-icon {
  margin: 0;
  vertical-align: middle;
  width: 24px;
  text-align: center;
}

/* 修复折叠子菜单的图标位置 */
.el-menu--collapse .el-sub-menu__title .el-icon {
  margin: 0;
  vertical-align: middle;
  width: 24px;
  text-align: center;
}

.el-menu--popup {
  min-width: 200px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #bfcbd9;
}

.loading-icon {
  font-size: 24px;
  margin-bottom: 10px;
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
